﻿using HandyControl.Controls;
using IntoTheVoid.Models;
using IntoTheVoid.Units;
using Microsoft.VisualBasic;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Security.Policy;
using System.Windows.Forms;


namespace IntoTheVoid.State
{
    // 检查状态,获取请求
    public class FirstCheckState : State
    {

        private GameDownloadConfigModel gameDownlaodConifgModel;
        private BaseInfoContentModel baseInfoContentModel;
        public BaseInfoContentModel BaseInfoContentModel { get; private set; }
        private BtnStage btnStage = BtnStage.None;  
        public bool CheckLauncherUpdate = false;        // 是否强制检测启动器更新
        public bool CheckLauncherUpdateOl = false;      // 后台配置是否强制启动器更新检测
        public bool CheckIsByUser = false;
        private bool isFirstCheck = false;
        public FirstCheckState(StateContext context, bool checkLauncher = false, bool checkByUser = false) 
        {
			isFirstCheck = true;
			buttonContent = "检查更新";
			CheckLauncherUpdate = checkLauncher;
			CheckIsByUser = checkByUser;
			buttonEnabla = false;
            Context = context;
			gameDownlaodConifgModel = GameDownloadConfigModel.Instance;
            baseInfoContentModel = BaseInfoContentModel.Instance;
            gameDownlaodConifgModel.DownLoadConfigCompleted += DownLoadConfigCompleted;
            Common.CheckGameIsExist();


		}
		public override void Start(StateContext context)
		{
			Context = context;
			Context.OnButtonStateArgs(new ButtonStateChangeEventArgs(buttonContent, buttonEnabla, false, false, "StartDownloadButtonGray"));
			Context.StateType = StateType.CheckingUpdate;

			// 请求数据
			gameDownlaodConifgModel.SendStartConfigMessage(baseInfoContentModel.GetValue<string>("version", ""));

		}

		private void DownLoadConfigCompleted(object sender, GameDownloadConfigEventArgs e)
        {
            if(!isFirstCheck)
                return;
			isFirstCheck = false;
			

			LogHelper.Info("DownLoadConfigCompleted response:" + e.Code);

            if (e.Code == -1)
            {
				LogHelper.Info("Enter e.Code == -1");
				Context.OnTipsStateArgs(new TipsEventArgs("网络连接失败"));
                buttonEnabla = true;
                // 重新请求数据
                Context.OnButtonStateArgs(new ButtonStateChangeEventArgs(buttonContent, buttonEnabla, false, false, "StartDownloadButtonGray"));
            }
            else
            {
				LogHelper.Info("Enter e.Code != -1");

				btnStage = baseInfoContentModel.GetValue<BtnStage>("btnStage", BtnStage.None);


                var localVersion = baseInfoContentModel.GetValue<string>("version", "");
                var httpDownLoadInfo = gameDownlaodConifgModel.DownLoadInfo;
				var olVersion = httpDownLoadInfo.OpenedLatest;

				if (httpDownLoadInfo == null)
                {
					LogHelper.Info("httpDownLoadInfo == null");
					Context.OnTipsStateArgs(new TipsEventArgs("网络连接失败，请联系管理员"));
                    buttonEnabla = false;
                    return;
				}
                CheckLauncherUpdateOl = httpDownLoadInfo.LauncherForceUpdate;
				SwitchLauncherState(olVersion, localVersion);

				if (CheckLauncherUpdate && CheckLauncherUpdateOl)
                {
					CheckForLauncherUpdate(httpDownLoadInfo);
				}

				LogHelper.Info("FirstCheck State:" + Context.StateType.ToString());
			}
		}

		void SwitchLauncherState(string olVersion,string localVersion)
		{
			//if (CheckIsByUser)
			//{
			//	if (btnStage == BtnStage.None)
			//	{
			//		Context.OnTipsStateArgs(new TipsEventArgs("请先下载游戏"));
			//	}
			//	else if (btnStage == BtnStage.Play)
			//	{
			//		Context.OnTipsStateArgs(new TipsEventArgs("游戏已经是最新版本，请开始游戏"));
			//	}
			//}

			// 本地存在游戏
			if (Common.CheckGameFolderIsInstalled(olVersion))
			{
				Context.StateType = StateType.CanOpenGame;
				Context.CurState = new OpenGameState(Context);
				return;
			}



			if (localVersion == "" || localVersion == null || !Common.CheckGameFolderIsInstalled(localVersion))
			{
				// 检查文件是否有旧版本的文件
				var checkV = Common.CheckExistVersion();
				if (checkV != "" && checkV != null)
				{
					if (checkV != olVersion)
					{
						// 需要更新
						BaseInfoContentModel.Instance.SetValue("version", checkV);
						LogHelper.Info(" checkV != olVersion need update");
						Context.StateType = StateType.CheckingUpdate;
						Context.CurState = new FirstCheckState(Context);
						Context.CurState.Start(Context);
						return;
					}
				}

				// 下载游戏
				LogHelper.Info(" Check switch Enter  StateType.NeedDownload (btnStage)");

				Context.StateType = StateType.NeedDownload;
				Context.CurState = new DownloadState(Context);
				return;
			}
			else if (olVersion != localVersion)
			{
				// 需要更新
				LogHelper.Info("need update");
				Context.StateType = StateType.NeedUpdate;
				Context.CurState = new UpdateState(Context);
				// 进游戏直接调用直接更新
				Context.CurState.Start(Context);
				return;
			}
			else
			{
				Context.StateType = StateType.CanOpenGame;
				Context.CurState = new OpenGameState(Context);
				return;
			}
		}
        void CheckForLauncherUpdate(DownLoadInfo info)
        {
			if (!Common.CheckLauncherVersion(info.LauncherLatest))
			{
				Action confirmAction = () =>
				{
					Common.OpenLauncherUpdate(info.LauncherLink);
				};
				Context.OnTipsStateArgs(new TipsEventArgs(string.Format("启动器更新：修复了部分问题"), confirmAction, () => Environment.Exit(0)));
			}
		}

    }
}
